package novanok.com.tracktweet;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.SearchManager;
import android.content.Intent;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.Legend;
import com.github.mikephil.charting.utils.XLabels;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import twitter4j.FilterQuery;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class MainActivity extends Activity implements SharedPreferences.OnSharedPreferenceChangeListener {

    int cantidad_tweets = 0;
    private AdView adView;
    private MapReduceCantidadTweets mpCantTweets = new MapReduceCantidadTweets(this);
    private MapReduceSexo mpSexo;
    private Map<String, Integer> ranking_tweets = new TreeMap<String, Integer>();
    private MapReduceHashTags mpHashtags = new MapReduceHashTags();
    private MapReduceMenciones mpMenciones = new MapReduceMenciones();
    private MapReduceUsuarioMasTweetea mpUsuario = new MapReduceUsuarioMasTweetea();
    private MapReduceUbicacionGeografica mpUbicacion = new MapReduceUbicacionGeografica();

    final int[] colores = {
            R.color.fresh_1, R.color.fresh_2,
            R.color.fresh_3, R.color.fresh_4,
            R.color.fresh_5, R.color.colorful_1,
            R.color.colorful_2, R.color.colorful_3,
            R.color.colorful_4, R.color.colorful_5
    };
    private String token;// = "302626129-ZddKWQhLwVe24PbN04nmhPJuKmcPUdOjMwvHOzeu";
    String tokenSecret;// = "nxqYVQOGE6Tt9bMbPHp0wjEdXEDDKPsjCxyRogmqu7i2b";

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mPlanetTitles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        adView = new AdView(this);
        adView.setAdUnitId("ca-app-pub-8819200492193671/2889218744");
        adView.setAdSize(AdSize.BANNER);
        LinearLayout layout = (LinearLayout)findViewById(R.id.banner);
        layout.addView(adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);

        mTitle = mDrawerTitle = getTitle();
        mPlanetTitles = getResources().getStringArray(R.array.menu);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPlanetTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed( View view ) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened( View drawerView ) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        // mDrawerLayout.bringToFront();

        findViewById(R.id.lblDetalle).bringToFront();

        PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);

        mpSexo = new MapReduceSexo(this, getResources().getStringArray(R.array.masculinos), getResources().getStringArray(R.array.femeninos));

        ((BarChart)findViewById(R.id.graficoHashtag)).setDescription("");
        ((BarChart)findViewById(R.id.graficoHashtag)).setDrawLegend(true);
        ((BarChart)findViewById(R.id.graficoHashtag)).setDrawBarShadow(false);
        ((BarChart)findViewById(R.id.graficoHashtag)).setDrawYLabels(false);
        ((BarChart)findViewById(R.id.graficoHashtag)).setDrawXLabels(false);
        ((BarChart)findViewById(R.id.graficoHashtag)).setDrawHorizontalGrid(false);
        ((BarChart)findViewById(R.id.graficoHashtag)).setDrawGridBackground(false);
        ((BarChart)findViewById(R.id.graficoHashtag)).setDrawVerticalGrid(false);
        ((BarChart)findViewById(R.id.graficoHashtag)).setValueDigits(0);
        ((BarChart)findViewById(R.id.graficoHashtag)).setDrawValueAboveBar(true);

        ((BarChart)findViewById(R.id.graficoMenciones)).setDescription("");
        ((BarChart)findViewById(R.id.graficoMenciones)).setDrawLegend(true);
        ((BarChart)findViewById(R.id.graficoMenciones)).setDrawBarShadow(false);
        ((BarChart)findViewById(R.id.graficoMenciones)).setDrawYLabels(false);
        ((BarChart)findViewById(R.id.graficoMenciones)).setDrawXLabels(false);
        ((BarChart)findViewById(R.id.graficoMenciones)).setDrawHorizontalGrid(false);
        ((BarChart)findViewById(R.id.graficoMenciones)).setDrawVerticalGrid(false);
        ((BarChart)findViewById(R.id.graficoMenciones)).setValueDigits(0);
        ((BarChart)findViewById(R.id.graficoMenciones)).setDrawValueAboveBar(true);
        ((BarChart)findViewById(R.id.graficoMenciones)).setDrawGridBackground(false);

        ((BarChart)findViewById(R.id.graficoUbicacion)).setDescription("");
        ((BarChart)findViewById(R.id.graficoUbicacion)).setDrawLegend(true);
        ((BarChart)findViewById(R.id.graficoUbicacion)).setDrawBarShadow(false);
        ((BarChart)findViewById(R.id.graficoUbicacion)).setDrawYLabels(false);
        ((BarChart)findViewById(R.id.graficoUbicacion)).setDrawXLabels(false);
        ((BarChart)findViewById(R.id.graficoUbicacion)).setDrawHorizontalGrid(false);
        ((BarChart)findViewById(R.id.graficoUbicacion)).setDrawVerticalGrid(false);
        ((BarChart)findViewById(R.id.graficoUbicacion)).setValueDigits(0);
        ((BarChart)findViewById(R.id.graficoUbicacion)).setDrawValueAboveBar(true);
        ((BarChart)findViewById(R.id.graficoUbicacion)).setDrawGridBackground(false);

        ((BarChart)findViewById(R.id.graficoUsuario)).setDescription("");
        ((BarChart)findViewById(R.id.graficoUsuario)).setDrawLegend(true);
        ((BarChart)findViewById(R.id.graficoUsuario)).setDrawBarShadow(false);
        ((BarChart)findViewById(R.id.graficoUsuario)).setDrawYLabels(false);
        ((BarChart)findViewById(R.id.graficoUsuario)).setDrawXLabels(false);
        ((BarChart)findViewById(R.id.graficoUsuario)).setDrawHorizontalGrid(false);
        ((BarChart)findViewById(R.id.graficoUsuario)).setDrawVerticalGrid(false);
        ((BarChart)findViewById(R.id.graficoUsuario)).setValueDigits(0);
        ((BarChart)findViewById(R.id.graficoUsuario)).setDrawValueAboveBar(true);
        ((BarChart)findViewById(R.id.graficoUsuario)).setDrawGridBackground(false);

        ((BarChart)findViewById(R.id.graficoCantidadTweets)).setDescription("");
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).setDrawLegend(false);
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).setDrawBarShadow(false);
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).setDrawYLabels(false);
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).setDrawXLabels(true);
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).setDrawHorizontalGrid(false);
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).setDrawVerticalGrid(false);
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).setValueDigits(0);
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).setDrawValueAboveBar(true);
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).setDrawGridBackground(false);
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).getXLabels().setPosition(XLabels.XLabelPosition.BOTTOM);
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).getXLabels().setCenterXLabelText(true);
        ((BarChart)findViewById(R.id.graficoCantidadTweets)).getXLabels().setAdjustXLabels(false);

        ((PieChart)findViewById(R.id.graficoSexo)).setDescription("");
        ((PieChart)findViewById(R.id.graficoSexo)).setDrawLegend(true);
        ((PieChart)findViewById(R.id.graficoSexo)).setValueDigits(0);
        ((PieChart)findViewById(R.id.graficoSexo)).setUsePercentValues(true);
        ((PieChart)findViewById(R.id.graficoSexo)).setDrawXValues(false);
        ((PieChart)findViewById(R.id.graficoSexo)).setValueTextColor(getResources().getColor(R.color.black));

        Uri uri = getIntent().getData();
        String verifier = uri.getQueryParameter("oauth_verifier");
        new TwitterGetAccessTokenTask().execute(verifier);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu( Menu menu ) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected( MenuItem item ) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        // Handle action buttons
        switch( item.getItemId() ) {
            case R.id.action_settings:
                // create intent to perform web search for this planet
                Intent intent = new Intent(this, SettingActivity.class);
                intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
                // catch event that there's no activity to handle intent
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivity(intent);
                } else {
                    Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
                }
                return true;

            case R.id.logout:
                new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle(R.string.quit)
                    .setMessage(R.string.really_quit)
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
                            twitterStream.shutdown();
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }

                    })
                    .setNegativeButton(R.string.no, null)
                    .show();

                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void iniciar(){
        AccessToken accessToken = new AccessToken(token, tokenSecret);

        TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
        twitterStream.setOAuthConsumer(getResources().getString(R.string.consumer_key), getResources().getString(R.string.consumer_key_secret));
        twitterStream.setOAuthAccessToken(accessToken);
        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(final Status status) {
                String country = status.getPlace().getCountry();
                if( isCountrySelected(country)) {

                    MainActivity.this.cantidad_tweets += 1;

                    mpHashtags.analizar(status.getHashtagEntities());
                    mpMenciones.analizar(status.getUserMentionEntities());

                    if (status.getPlace() != null && country != null) {

                        mpUbicacion.analizar(country);
                    }

                if ( status.getPlace() != null && status.getPlace().getCountry() != null )
                    mpUbicacion.analizar(status.getPlace().getCountry());

                    String[] nombres = status.getUser().getName().split(" ");
                    for (String n : nombres)
                        mpSexo.analizar(n);

                    mpUsuario.analizar(status.getUser().getScreenName());

                    MainActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            ((TextView) findViewById(R.id.lblDetalle)).setText("Cant Tweets : " + MainActivity.this.cantidad_tweets);

                        actualizarHashTags();
                        actualizarMenciones();
                        actualizarCantidadTweetsPorHora();
                        actualizarCantidadSexo();
                        actualizarUbicacionGeografica();
                        actualizarUsuarioMasTwitter();
                        }
                    });
                }
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
            }

            @Override
            public void onScrubGeo(long userId, long upToStatusId) {
                System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
            }

            @Override
            public void onStallWarning(StallWarning warning) {
                System.out.println("Got stall warning:" + warning);
            }

            @Override
            public void onException(Exception ex) {
                ex.printStackTrace();
            }
        };
        twitterStream.addListener(listener);
        double[][] locations = { { -180, -90 }, { 180, 90 } };

        FilterQuery fill = new FilterQuery();
        fill.locations(locations);

        twitterStream.filter( fill );
    }

    private boolean isCountrySelected(String country) {
        if (country.equals("Brasil")) {
            System.out.print(country);
        }
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        Set<String> countriesPref = sharedPref.getStringSet("countries", null);
        return countriesPref.contains(country);
    }

    public synchronized int getCantidad_tweets(){
        return this.cantidad_tweets;
    }

    private synchronized void actualizarCantidadTweetsPorHora(){
        synchronized (mpCantTweets) {
            ArrayList<String> str = new ArrayList<String>();
            ArrayList<BarDataSet> data = new ArrayList<BarDataSet>();

            int i = 0;
            for ( Map.Entry<String, Integer> val : mpCantTweets.getCantidadTweets().entrySet() ) {
                if ( val.getValue() > 0 ) {
                    str.add(val.getKey());
                    ArrayList<Entry> valores = new ArrayList<Entry>();
                    valores.add(new Entry(val.getValue(), i));
                    data.add(new BarDataSet(valores, val.getKey()));

                    i++;
                }
            }

            if ( str.size() > 0 && data.size() > 0 ) {
                ((BarChart) findViewById(R.id.graficoCantidadTweets)).setData(new BarData(str, data));

                Legend l = ((BarChart)findViewById(R.id.graficoCantidadTweets)).getLegend();
                l.setFormSize(10f); // set the size of the legend forms/shapes
                l.setForm(Legend.LegendForm.CIRCLE); // set what type of form/shape should be used
                l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
                l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
                l.setYEntrySpace(5f);

                findViewById(R.id.graficoCantidadTweets).invalidate();
            }
        }
    }

    private synchronized void actualizarHashTags(){
        synchronized ( mpHashtags ) {
            Map<String, Integer> lista = mpHashtags.getHashtagsOrdenados();
            ArrayList<String> str = new ArrayList<String>();
            ArrayList<BarDataSet> data = new ArrayList<BarDataSet>();

            int i = 0;

            for ( Map.Entry<String, Integer> val : lista.entrySet() ) {
                String hash = ( val.getKey().length() >= 20 ) ? val.getKey().substring(0, 20) + "..." : val.getKey();

                str.add(hash);
                ArrayList<Entry> valores = new ArrayList<Entry>();
                valores.add(new Entry(val.getValue(), i));
                BarDataSet bds = new BarDataSet(valores, "#" + val.getKey());
                bds.setColor(getResources().getColor(colores[i]));
                data.add(bds);

                i++;

                if ( i >= 10 ) { break; }
            }

            if (str.size() > 0 && data.size() > 0){
                ((BarChart)findViewById(R.id.graficoHashtag)).setData(new BarData(str, data));

                Legend l = ((BarChart)findViewById(R.id.graficoHashtag)).getLegend();
                l.setFormSize(10f); // set the size of the legend forms/shapes
                l.setForm(Legend.LegendForm.CIRCLE); // set what type of form/shape should be used
                l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
                l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
                l.setYEntrySpace(5f);

                findViewById(R.id.graficoHashtag).invalidate();
            }
        }
    }

    private synchronized void actualizarMenciones(){
        synchronized ( mpMenciones ) {
            Map<String, Integer> lista = mpMenciones.getMencionesOrdenados();

            ArrayList<String> str = new ArrayList<String>();
            ArrayList<BarDataSet> data = new ArrayList<BarDataSet>();


            int i = 0;
            for ( Map.Entry<String, Integer> val : lista.entrySet() ) {
                str.add(val.getKey());
                ArrayList<Entry> valores = new ArrayList<Entry>();
                valores.add(new Entry(val.getValue(), i));

                BarDataSet bds = new BarDataSet(valores, "@" + val.getKey());
                bds.setColor(getResources().getColor(colores[i]));

                data.add(bds);

                i++;

                if ( i >= 10 ) { break; }
            }

            if (str.size() > 0 && data.size() > 0) {
                ((BarChart) findViewById(R.id.graficoMenciones)).setData(new BarData(str, data));

                Legend l = ((BarChart)findViewById(R.id.graficoMenciones)).getLegend();
                l.setFormSize(10f); // set the size of the legend forms/shapes
                l.setForm(Legend.LegendForm.CIRCLE); // set what type of form/shape should be used
                l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
                l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
                l.setYEntrySpace(5f);

                findViewById(R.id.graficoMenciones).invalidate();
            }
        }
    }

    private synchronized void actualizarCantidadSexo(){
        synchronized ( mpSexo ){
            int cantidadMasculinos = mpSexo.getCantidadMasculinos();
            int cantidadFemeninos = mpSexo.getCantidadFemeninos();
            int cantidadOtros = mpSexo.getOtros();

            ArrayList<String> str = new ArrayList<String>();

            str.add(getResources().getString(R.string.masculino));
            str.add(getResources().getString(R.string.femenino));
            str.add(getResources().getString(R.string.otros));

            ArrayList<Entry> valores = new ArrayList<Entry>();
            valores.add(new Entry(cantidadMasculinos, 0));
            valores.add(new Entry(cantidadFemeninos, 1));
            valores.add(new Entry(cantidadOtros, 2));

            PieDataSet pds = new PieDataSet(valores, "Cant");
            pds.setSliceSpace(3f);
            pds.setColors(ColorTemplate.createColors(this.getApplicationContext(), ColorTemplate.VORDIPLOM_COLORS));

            ((PieChart) findViewById(R.id.graficoSexo)).setData(new PieData(str, pds));

            Legend l = ((PieChart)findViewById(R.id.graficoSexo)).getLegend();
            l.setFormSize(10f); // set the size of the legend forms/shapes
            l.setForm(Legend.LegendForm.CIRCLE); // set what type of form/shape should be used
            l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
            l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
            l.setYEntrySpace(5f);

            findViewById(R.id.graficoSexo).invalidate();
        }
    }

    private synchronized void actualizarUbicacionGeografica(){
        synchronized ( mpUbicacion ) {
            Map<String, Integer> lista = mpUbicacion.getUbicacionOrdenados();

            ArrayList<String> str = new ArrayList<String>();
            ArrayList<BarDataSet> data = new ArrayList<BarDataSet>();


            int i = 0;
            for ( Map.Entry<String, Integer> val : lista.entrySet() ) {
                str.add(val.getKey());
                ArrayList<Entry> valores = new ArrayList<Entry>();
                valores.add(new Entry(val.getValue(), i));

                BarDataSet bds = new BarDataSet(valores, val.getKey());
                bds.setColor(getResources().getColor(colores[i]));

                data.add(bds);

                i++;

                if ( i >= 10 ) { break; }
            }

            if (str.size() > 0 && data.size() > 0) {
                ((BarChart) findViewById(R.id.graficoUbicacion)).setData(new BarData(str, data));

                Legend l = ((BarChart)findViewById(R.id.graficoUbicacion)).getLegend();
                l.setFormSize(10f); // set the size of the legend forms/shapes
                l.setForm(Legend.LegendForm.CIRCLE); // set what type of form/shape should be used
                l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
                l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
                l.setYEntrySpace(5f);

                findViewById(R.id.graficoUbicacion).invalidate();
            }
        }
    }

    private synchronized void actualizarUsuarioMasTwitter(){
        synchronized ( mpUsuario ) {
            Map<String, Integer> lista = mpUsuario.getListaOrdenados();

            ArrayList<String> str = new ArrayList<String>();
            ArrayList<BarDataSet> data = new ArrayList<BarDataSet>();


            int i = 0;
            for ( Map.Entry<String, Integer> val : lista.entrySet() ) {
                str.add(val.getKey());
                ArrayList<Entry> valores = new ArrayList<Entry>();
                valores.add(new Entry(val.getValue(), i));

                BarDataSet bds = new BarDataSet(valores, "@" + val.getKey());
                bds.setColor(getResources().getColor(colores[i]));

                data.add(bds);

                i++;

                if ( i >= 10 ) { break; }
            }

            if (str.size() > 0 && data.size() > 0) {
                ((BarChart) findViewById(R.id.graficoUsuario)).setData(new BarData(str, data));

                Legend l = ((BarChart)findViewById(R.id.graficoUsuario)).getLegend();
                l.setFormSize(10f); // set the size of the legend forms/shapes
                l.setForm(Legend.LegendForm.CIRCLE); // set what type of form/shape should be used
                l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
                l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
                l.setYEntrySpace(5f);

                findViewById(R.id.graficoUsuario).invalidate();
            }
        }
    }

    @Override
    public void onBackPressed() {

    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
        if (s.equals("countries")) {
            clearCharts();
        }

        this.actualizarVisualizacion();
    }

    public synchronized void clearCharts() {
        cantidad_tweets = 0;
        //mpCantTweets.clear();
        mpHashtags.clear();
        mpMenciones.clear();
        mpSexo.clear();
        mpUbicacion.clear();
        mpUsuario.clear();
    }

    class TwitterGetAccessTokenTask extends AsyncTask<String, String, String> {

        @Override
        protected void onPostExecute( String userName ) {
            iniciar();
            MainActivity.this.actualizarVisualizacion();
        }

        @Override
        protected String doInBackground(String... params) {

            Twitter twitter = TwitterUtil.getInstance().getTwitter();
            RequestToken requestToken = TwitterUtil.getInstance().getRequestToken();
            try {
                AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, params[0]);
                token = accessToken.getToken();
                tokenSecret = accessToken.getTokenSecret();
            } catch (TwitterException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            selectItem(position);

        }
    }

    private void selectItem(int position) {
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);

        mDrawerLayout.closeDrawer(mDrawerList);

        switch (position){
            case 0:{
                Intent i = new Intent(this, NewTrackerActivity.class);
                startActivity(i);
                break;
            }

            case 1:{
                Intent i = new Intent(this, SettingActivity.class);
                startActivity(i);
                break;
            }

            case 2:{
                new AlertDialog.Builder(this)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(R.string.quit)
                        .setMessage(R.string.really_quit)
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
                                twitterStream.shutdown();
                                android.os.Process.killProcess(android.os.Process.myPid());
                            }

                        })
                        .setNegativeButton(R.string.no, null)
                        .show();
                break;
            }
        }
    }

    private boolean getPreferencia( String valor ){
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        return sharedPref.getBoolean(valor, true);
    }

    private void actualizarVisualizacion(){
        findViewById(R.id.frameGraficoHashtags).setVisibility(getPreferencia("rnk_hashtags") ? View.VISIBLE : View.GONE);
        findViewById(R.id.frameGraficoMenciones).setVisibility(getPreferencia("rnk_menciones") ? View.VISIBLE : View.GONE);
        findViewById(R.id.frameGraficoCantidadTweets).setVisibility(getPreferencia("rnk_cantidad_tweets") ? View.VISIBLE : View.GONE);
        findViewById(R.id.frameGraficoSexo).setVisibility(getPreferencia("rnk_sexo") ? View.VISIBLE : View.GONE);
        findViewById(R.id.frameGraficoUbicacion).setVisibility(getPreferencia("rnk_paises") ? View.VISIBLE : View.GONE);
        findViewById(R.id.frameGraficoUsuario).setVisibility(getPreferencia("rnk_usuario") ? View.VISIBLE : View.GONE);
    }
}